﻿/*
   Copyright 2012 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using System.ServiceProcess;
using Flower.Logging;
using Spring.Context;
using Spring.Context.Support;
using System.Threading;

namespace Flower.Services.Host
{
    internal static class Program
    {
        private static readonly Log Log;
        private static readonly ManualResetEventSlim Wait = new ManualResetEventSlim();

        private static bool _debugMode;

        private static void ParseArgs(string[] args)
        {
            foreach (string t in args)
            {
                if (t == "/debug")
                {
                    _debugMode = true;
                }
            }
        }

        static Program()
        {
            System.IO.Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            
            Log = LogManager.CreateLog("Main");
        }

        public static void Main(string[] args)
        {
            try
            {
                Log.Info("Starting the Flower hosting service...");

                ParseArgs(args);
                
                IApplicationContext appContext =
                    new XmlApplicationContext(AppDomain.CurrentDomain.BaseDirectory + @"\Flower.Services.Host.config");

                var service = (Service)appContext.GetObject("service");

                if (!_debugMode)
                {
                    ServiceBase.Run(service);
                }
                else
                {
                    Log.Info("Running the Flower services host in debug mode.");

                    service.DoStart();
                    Wait.Wait();
                }
            }
            catch(Exception ex)
            {
                Log.Fatal("Failed to start the Flower hosting service.", ex);
                LogManager.Flush();
            }
        }
    }
}
